package eu.kleinkoerkamp.core.repository;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import eu.kleinkoerkamp.core.domain.DomainObject;
import eu.kleinkoerkamp.core.util.EMF;

public class AbstractDefaultRepository<T extends DomainObject, ID extends Serializable> implements DefaultRepository<T, ID> {
	
	protected Class<T> m_entityClass;
 
	public AbstractDefaultRepository() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		m_entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
	}
	
	public void delete(T domainObject) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.remove(domainObject);
		} finally {
		      em.close();
	    }
	}

	public T getObject(ID id) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			return em.find(m_entityClass, id);
		} finally {
		      em.close();
	    }
	}

	public Collection<T> getObjects() {
		
		
		EntityManager em = EMF.get().createEntityManager();
		try {
			Query q = em.createQuery(
					"SELECT FROM " + m_entityClass.getName());
			List<T> returnValue = (List<T>) q.getResultList();
			returnValue.size();
			return returnValue;
		} finally {
		      em.close();
	    }
	}

	public void save(T domainObject) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.persist(domainObject);
		} finally {
		      em.close();
	    }
	}

}
